#include "LogViewerDialog.h"
#include <QTextEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QClipboard>
#include <QApplication>
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>

LogViewerDialog::LogViewerDialog(const QString& logText, QWidget* parent)
    : QDialog(parent)
{
    setWindowTitle("调试日志");
    resize(700, 400);

    textEdit = new QTextEdit(this);
    textEdit->setReadOnly(true);
    textEdit->setText(logText);
    textEdit->setStyleSheet("font-family: Consolas; font-size: 11px;");

    copyButton = new QPushButton("复制全部", this);
    saveButton = new QPushButton("保存为文本", this);

    connect(copyButton, &QPushButton::clicked, this, &LogViewerDialog::copyToClipboard);
    connect(saveButton, &QPushButton::clicked, this, &LogViewerDialog::saveToFile);

    QHBoxLayout* buttonLayout = new QHBoxLayout;
    buttonLayout->addStretch();
    buttonLayout->addWidget(copyButton);
    buttonLayout->addWidget(saveButton);

    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(textEdit);
    mainLayout->addLayout(buttonLayout);

    setLayout(mainLayout);
}

void LogViewerDialog::copyToClipboard()
{
    QClipboard* clipboard = QApplication::clipboard();
    clipboard->setText(textEdit->toPlainText());
}

void LogViewerDialog::saveToFile()
{
    QString fileName = QFileDialog::getSaveFileName(this, "保存日志为", "log.txt", "Text Files (*.txt);;All Files (*)");
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            file.write(textEdit->toPlainText().toUtf8());
            file.close();
            QMessageBox::information(this, "保存成功", "日志已保存到:\n" + fileName);
        } else {
            QMessageBox::warning(this, "保存失败", "无法写入文件:\n" + fileName);
        }
    }
}
